function DisableAllObjectFromBeingDragable() {
    // Disable all object from being dragable, except player cards
    document.addEventListener('dragstart', function(e) { 
            if ( (!e.target.id.startsWith("card")) || (!ISMYTURN) ) {
                    e.preventDefault(); 
            }
    });   
}
function updateBoard(BoardArray,PNum) {
    tmpBoard = [];

    for (var i=0;i<4;i++) {
        tmpBoard[i] = [];
    }

    for (var i=0;i<4;i++) {
        for (var j=0;j<3;j++) {

            tmpBoard[i][j] = {  'IsEmpty' : true , 'Type': null , 'Life' : null, 'Element' : null}; //init
            tmpBoard[i][j]["Type"] = BoardArray[(i*3*2)+(j*2)];   // soldier type
            tmpBoard[i][j]["Life"] = BoardArray[(i*3*2)+(j*2)+1]; // get life
            
            // init Soldier Cell in Player Board
            tmpBoard[i][j]["Element"] = document.getElementById("p" + PNum + "_board_" + i.toString() + j.toString() );
            // SetBackround to Transparent
            tmpBoard[i][j]["Element"].style.backgroundColor = "transparent";
                    
            tmpBoard[i][j]["LifeElement"] = document.getElementById("p" + PNum + "_board_" + i.toString() + j.toString() + "_txt");
            tmpBoard[i][j]["ImageSpanElement"] = document.getElementById("p" + PNum + "_board_" + i.toString() + j.toString() + "_img_span");
            
            if ( tmpBoard[i][j]["Type"] != "xxx" ) {    //if not exmpt box
                tmpBoard[i][j]["IsEmpty"] = false;
                tmpBoard[i][j]["LifeElement"].innerHTML = parseInt( tmpBoard[i][j]["Life"] ) ; //show life
                // show soldier:
                var image_num;
        
                switch (true) {
                    case (tmpBoard[i][j]["Life"] <= SoldiersImageByLife[ tmpBoard[i][j]["Type"] ][2]):
                        image_num = 3;
                        break;
                    case (tmpBoard[i][j]["Life"] <= SoldiersImageByLife[ tmpBoard[i][j]["Type"] ][1]):
                        image_num = 2;
                        break;
                    case (tmpBoard[i][j]["Life"] <= SoldiersImageByLife[ tmpBoard[i][j]["Type"] ][0]):
                        image_num = 1;
                        break;                
                    default:
                        image_num = 1;
                }  
                
                tmpBoard[i][j]["ImageSpanElement"].innerHTML =
                        "<img src='images/game/soldiers/" + tmpBoard[i][j]["Type"] + "/" + image_num.toString() + 
                        ".png' onclick='SoldierClicked(" + i + "," + j+ "," + PNum + ");'" +
                         " onMouseOver='ShowPopup(this,\"card" + tmpBoard[i][j]["Type"] + "_popup\",50,50);' onMouseOut='HidePopup(\"card" + tmpBoard[i][j]["Type"] + "_popup\");'" + ">" ;
            }
            else {  //empty
                tmpBoard[i][j]["IsEmpty"] = true;
                tmpBoard[i][j]["LifeElement"].innerHTML = "";
                tmpBoard[i][j]["ImageSpanElement"].innerHTML = "";
            }

        }
    }        
    return tmpBoard;
}
function updateTowers(TowersArray,PNum) {
    Towers = [];

    for (var i=0;i<4;i++) {

        Towers[i] = { 'Life' : null , 'LifeElement' : null , 'ImageElement' : null};
        Towers[i]["Life"] = TowersArray[i]; // get life
        
        document.getElementById("p" + PNum + "_tower_" + i ).style.backgroundColor = "transparent";
        
        Towers[i]["LifeElement"] = document.getElementById("p" + PNum + "_tower_"  + i.toString() + "_txt");
        Towers[i]["ImageElement"] = document.getElementById("p" + PNum + "_tower_" + i.toString() + "_img");

        //Show/Set Tower Image+Damange
        if ( parseInt(Towers[i]["Life"]) > 0 ) {
            Towers[i]["LifeElement"].innerHTML = Towers[i]["Life"];
        }
        else {
            Towers[i]["LifeElement"].innerHTML = "";
        }
        
        var image_num;
        
        switch (true) {
            case (Towers[i]["Life"] <= 0):
                image_num = 4;
                break;
            case (Towers[i]["Life"] <= 50):
                image_num = 3;
                break;
            case (Towers[i]["Life"] <= 100):
                image_num = 2;
                break;
            case (Towers[i]["Life"] <= 150):
                image_num = 1;
                break;                
            default:
                image_num = 1;
        }        

        
        Towers[i]["ImageElement"].innerHTML = "<img src='images/game/tower/" + image_num.toString() + ".png'>";
    }    
    return Towers;        
}
function updateCards(CardsArray) {

    //CARD_IMAGE_PATH
    Cards = [];

    for (var i=0;i<5;i++) {

        Cards[i] = { 'IsEmpty' : true , 'index': null,  'Card_id': null , 'LifeElement' : null , 'ImageNumber' : null};
        Cards[i]["index"] = i;
        Cards[i]["Card_id"] = CardsArray[i];
        Cards[i]["Element"] = document.getElementById("card" + i.toString());

        if ( Cards[i]["Card_id"] != "xxx" ) {    //if not empty card
            Cards[i]["Element"].innerHTML = "<img id='card" + i.toString() + "'  src='images/game/cards/" + Cards[i]["Card_id"] +".jpg' draggable='true' style='cursor: move;' ondragstart='CardDrag(event)' onclick='CardClick(" + i + ");' />";;
            Cards[i]["IsEmpty"] = false;
            
        }
        else {
            Cards[i]["Element"].innerHTML = "";
            Cards[i]["IsEmpty"] = true;            
        }
    }        
    return Cards;   
}   
function paint_state(values) {

    LastParsedState = values;   //Save Last Parsed State - For Restarting Move

    //parse and draw players boards [1,2]
    var tmpBoard = values[1].match(/.{1,3}/g);
    PlayerBoard = updateBoard(tmpBoard, 1);

    tmpBoard = values[2].match(/.{1,3}/g);
    OpponentBoard = updateBoard(tmpBoard, 2);

    // Towers [3,4]
    var tmpTower = values[3].match(/.{1,3}/g);
    PlayerTowers = updateTowers(tmpTower, 1);
    tmpTower = values[4].match(/.{1,3}/g);
    OpponentTowers = updateTowers(tmpTower, 2);

    // Player Cards [5]
    var tmpCards = values[5].match(/.{1,3}/g);
    PlayerCards = updateCards(tmpCards, 0);

    IsBoardPainted = true;

    DisableAllObjectFromBeingDragable();
    
    // check if game ended
    if (IsGameEnded == 0) {
        SetBoardEnable(ISMYTURN);   //set player board to enable\disable
    }
    else {
        // game ended!
        SetBoardEnable(false);
        if ( IsGameEnded == WINNER_STATE ) {
            ShowLoseWin(true);
        }
        else {
            //LOSER_STATE
            ShowLoseWin(false);
        }
    }
}

//////////////////////////////////////////////////////
//              animate my attack                   //
//////////////////////////////////////////////////////
function animate_my_own_command(values) {
    
    //clear old data if any left;
    Animation_Init_Value = [];
    Animation_Min_Value = [];
    AnimationElement = [];
    
    // check if LastMove Exist
    if( values[6] == "null" || values[6] == "") {
        // update to the new board
        paint_state(values);
        myVar=setTimeout(function(){postGameState(); },ticker);
        return; //not...
    }
    
    // parse last move
    var lastCommand = values[6].split("|");
    // check for 1 or 2 commands
    for(var i=0; i<lastCommand.length; i++) {
        var singleCommand = lastCommand[i].split(" ");
        if(lastCommand[i].startsWith(COM_ATTACK)) {
            // [2] - op. board , [1] - my board , [4] - op. towers
            // Op. Attack Me.
            animateMeAttackOp(singleCommand, values[2], values[1], values[4]);
        }
        if(lastCommand[i].startsWith(COM_PLACE_CARD)) {
            // [1] - my board
            //animateMePlacingCard(singleCommand, values[1]);
        }
        if(lastCommand[i].startsWith(COM_DRAW_CARD)) {
            // op. only draw card
            //animateMeDrawACard(singleCommand);
        }
    }
    
    //Show Anim or just Update Board
    if (ArrayStartIndex >= 0) {
        // show the real animation and at the end paint new baord!
        AnimationStopEventFunction = function() { 
            paint_state(values);
            //set the ticker to activate after the animation;
            myVar=setTimeout(function(){postGameState();},ticker);
            //get first responce. dont waint for the ticker, in case of an error, handke in after the ticker.
        } ;
        StartAnimationTimer();    
    }
    else {
        paint_state(values); 
        myVar=setTimeout(function(){postGameState();},ticker);
    }
}
function animateMeAttackOp(splited, new_opBoard, new_myBoard, new_opTowers) {
    
    //split values
    var split_op_board = new_opBoard.match(/.{1,3}/g);
    var split_op_tower = new_opTowers.match(/.{1,3}/g);
    var split_my_board = new_myBoard.match(/.{1,3}/g);
        
    var x = splited[1];
    var y = splited[2];
    
    var card_id = split_my_board[(x * HP_SEG_LEN * 2) + (y * 2) ];
    
    // Init Animate - ArrayStartIndex
    ArrayStartIndex = -1; // ShowAttack will increase it by 1 for each dmg to show
    
    //check who got heart in my board (in row (op_x) , find the j!)
    for(var i=( COLS-1); i>=0 ; i--) {
        var p1 = OpponentBoard[x][i]["Life"];    // op. soldier life before attack
        var p2 = split_op_board[ (x * HP_SEG_LEN * 2) + (i * 2) + 1 ]; // op. soldier life after attack 
        
        // if life is diff so show hit in i,j
        if(p1 != p2) {   
            if(split_op_board[ (x * HP_SEG_LEN * 2) + (i * 2) + 1 ] == "xxx") {
                // "xxx" if soldier dead (Hit + Dead)
                ShowAttack(x, y, x, i, ATTACK_BOOL, KILL_TRUE_BOOL, SOLDIER_BOOL ,parseInt(p1) , 0);
                //animate "PlayerBoard[op_x][i]" got killed by "op_card_id"
            }
            else {
                // Not Dead, just Hit
                ShowAttack(x, y, x, i, ATTACK_BOOL, KILL_FALSE_BOOL, SOLDIER_BOOL, parseInt(p1) , parseInt(p2));
                //animate "PlayerBoard[op_x][i]" got damaged by "op_card_id"
                break; // don't continue to look more..
            }
        }
    }
    // also check if tower life changed
    //var p1 = PlayerTowers[op_x]["Life"];
    var p1 = OpponentTowers[x]["Life"];
    var p2 = split_op_tower[x];
    if(p1 != p2) {
        // Tower heart...
        ShowAttack(x, y, x, 0, ATTACK_BOOL, KILL_FALSE_BOOL, TOWER_BOOL , parseInt(p1) , parseInt(p2)) ;
    }
}

//////////////////////////////////////////////////////
//    animate_last_command  (Op Attack Me)          //
//////////////////////////////////////////////////////
//  animate the attack (only when op. attack me)
//  split_command - input command string
//  new_opponentBoard+new_playerBoard,new_playerTower from game_stat.php
function animateOpAttackMe(split_command, new_opponentBoard, new_playerBoard, new_playerTower) {
    
    var split_op_board = new_opponentBoard.match(/.{1,3}/g);
    var split_my_board = new_playerBoard.match(/.{1,3}/g);
    var split_my_tower = new_playerTower.match(/.{1,3}/g);
    
    var op_x = split_command[1];
    var op_y = split_command[2];
    
    var op_card_id = split_op_board[(op_x * HP_SEG_LEN * 2) + (op_y * 2) ];
    var op_life = split_op_board[(op_x * HP_SEG_LEN * 2) + (op_y * 2) + 1];
    
    // Init Animate - ArrayStartIndex
    ArrayStartIndex = -1; // ShowAttack will increase it by 1 for each dmg to show
    
    //check who got heart in my board (in row (op_x) , find the j!)
    for(var i=( COLS-1); i>=0 ; i--) {
        //var p1 = PlayerBoard[ op_x ][ i ]["Life"]; 
        
        //var p1 = PlayerBoard[ (op_x * HP_SEG_LEN * 2) + (i * 2) + 1 ];    // my soldier life before attack
        var p1 = PlayerBoard[op_x][i]["Life"];    // my soldier life before attack
        var p2 = split_my_board[ (op_x * HP_SEG_LEN * 2) + (i * 2) + 1 ]; // my soldier life after attack 
        
        // if life is diff so show hit in i,j
        if(p1 != p2) {   
            if(split_my_board[ (op_x * HP_SEG_LEN * 2) + (i * 2) + 1 ] == "xxx") {
                // "xxx" if soldier dead (Hit + Dead)
                ShowAttack(op_x, i, op_x, op_y, HIT_BOOL, KILL_TRUE_BOOL, SOLDIER_BOOL ,parseInt(p1) , 0);
                //animate "PlayerBoard[op_x][i]" got killed by "op_card_id"
            }
            else {
                // Not Dead, just Hit
                ShowAttack(op_x, i, op_x, op_y, HIT_BOOL, KILL_FALSE_BOOL, SOLDIER_BOOL, parseInt(p1) , parseInt(p2));
                //animate "PlayerBoard[op_x][i]" got damaged by "op_card_id"
                break; // don't continue to look more..
            }
        }
    }
    // also check if tower life changed
    //var p1 = PlayerTowers[op_x]["Life"];
    var p1 = PlayerTowers[op_x]["Life"];
    var p2 = split_my_tower[ op_x ];
    if(p1 != p2) {
        // Tower heart...
        ShowAttack(op_x, i, op_x, op_y, HIT_BOOL, KILL_TRUE_BOOL, TOWER_BOOL , parseInt(PlayerTowers[op_x]["Life"]) , parseInt(split_my_tower[ op_x ])) ;
    }
}
function animate_last_command(values) {
    
    //clear old data if any left;
    Animation_Init_Value = [];
    Animation_Min_Value = [];
    AnimationElement = [];
    
    // check if LastMove Exist
    if( values[6] == "null" || values[6] == "") {
        // update to the new board
        paint_state(values);         
        return; //not...
    }
    
    // parse last move
    var lastCommand = values[6].split("|");
    // check for 1 or 2 commands
    for(var i=0; i<lastCommand.length; i++) {
        var singleCommand = lastCommand[i].split(" ");
        if(lastCommand[i].startsWith(COM_ATTACK)) {
            // [2] - op. board , [1] - my board , [3] - my towers
            // Op. Attack Me.
            animateOpAttackMe(singleCommand, values[2], values[1], values[3]);
        }
    }
    //Show Anim or just Update Board
    if (ArrayStartIndex >= 0) {
        // show the real animation and at the end paint new baord!
        AnimationStopEventFunction = function() {paint_state(values);};
        StartAnimationTimer();    
    }
    else {
        paint_state(values); 
    }
}


var HIT_BOOL = 0;
var ATTACK_BOOL = 1;

var KILL_FALSE_BOOL = 0;
var KILL_TRUE_BOOL = 1;

var SOLDIER_BOOL = 0;
var TOWER_BOOL = 1;


// Animate the attack!
//  player i,j   soldier
//  op. i,j      soldier
//      (on tower->takes only i as tower index)
//  hit_or_attack -> HIT_BOOL(Hit) , ATTACK_BOOL(Attack)
//  is_killed (KILL_FALSE_BOOL\KILL_TRUE_BOOL -> to remove player image)
//  is_tower (SOLDIER_BOOL\TOWER_BOOL -> to animate tower hit)
//  CurLifeCount   - start life animation from x
//  AfterLifeCount - stop  life animation in   y 
function ShowAttack(p_i, p_j, op_i, op_j, hit_or_attack, is_killed, is_tower, CurLifeCount , AfterLifeCount ) {
    
    //p1_board_ij for player (me)
    //p2_board_ij for op.   
    //var p1_color,p2_color;  //tmp
    window.clearInterval(AnimationVariable);

    
    if (hit_or_attack == HIT_BOOL) {    // op. HIT me
        // Op Attack pos
        document.getElementById("p2_board_" + op_i + op_j).style.backgroundColor = ATTACK_COLOR;
    }
    else {  //hit_or_attack == ATTACK_BOOL -> me Attack op.
        // Player Attack pos
        document.getElementById("p1_board_" + p_i + p_j).style.backgroundColor = ATTACK_COLOR;        
    }
    

    ArrayStartIndex = ArrayStartIndex + 1 ; // add 1 to animation counter    
    
    // Tower or Soldier Hit\Attack ?!
    if ( is_tower == TOWER_BOOL) {

        if (hit_or_attack == HIT_BOOL) {    //hit my tower
            document.getElementById("p1_tower_" + p_i ).style.backgroundColor = HIT_COLOR;
            //set new animation
            Animation_Init_Value[ArrayStartIndex] = CurLifeCount;
            Animation_Min_Value[ArrayStartIndex] = AfterLifeCount;
            AnimationElement[ArrayStartIndex] = document.getElementById("p1_tower_" + p_i + "_txt");
        }
        else {  // hit op. tower
            document.getElementById("p2_tower_" + op_i ).style.backgroundColor = HIT_COLOR;
            //set new animation
            Animation_Init_Value[ArrayStartIndex] = CurLifeCount;
            Animation_Min_Value[ArrayStartIndex] = AfterLifeCount;
            AnimationElement[ArrayStartIndex] = document.getElementById("p2_tower_" + op_i + "_txt");            
        }
    }
    else {
        // no tower , just hit normal soldier
        if (hit_or_attack == HIT_BOOL) {    // op. HIT me
            // Player Hit pos
            document.getElementById("p1_board_" + p_i + p_j).style.backgroundColor = HIT_COLOR;
            //set new animation
            Animation_Init_Value[ArrayStartIndex] = CurLifeCount;
            Animation_Min_Value[ArrayStartIndex] = AfterLifeCount;
            AnimationElement[ArrayStartIndex] = document.getElementById("p1_board_" + p_i + p_j + "_txt");              
        }
        else {  //hit_or_attack == ATTACK_BOOL -> me Attack op.
            // Op Hit pos
            document.getElementById("p2_board_" + op_i + op_j).style.backgroundColor = HIT_COLOR; 
            //set new animation
            Animation_Init_Value[ArrayStartIndex] = CurLifeCount;
            Animation_Min_Value[ArrayStartIndex] = AfterLifeCount;
            AnimationElement[ArrayStartIndex] = document.getElementById("p2_board_" + op_i + op_j +"_txt");              
        }      
    }
    
}


// Show Lose Win Screen
// 0 - Lose
// 1 - Win
function ShowLoseWin(bool) {
    var image_name;
    if (bool) {
        //win
        image_name = "winner.jpg";
    }
    else {
        //lose
        image_name = "loser.png";
    }
    document.getElementById("divTopMSG").innerHTML = "";        //remove the waiting icon when board disabled
    document.getElementById("btnSendMSG").disabled = true;      //disable chat
    document.getElementById("btnForfeit").disabled = true;      //disable Surrender BTN
    document.getElementById("Player1_Board").innerHTML = "";
    document.getElementById("Player2_Board").innerHTML = "";
    document.getElementById("GameMessageCell").innerHTML = '<img src="images/game/' + image_name + '"<p><input type="button" id="btnProccedToPostGame" value="Press to Continue" onclick="window.location.replace(\'post_game.php\');"/></p>';
}

